import React from 'react';
import { connect } from 'dva';
import { Layout, Menu, Select , Button, DatePicker  } from 'antd';
const { SubMenu } = Menu;
const { Header, Content, Sider  } = Layout;
const { Option } = Select;
import Gmap from "@/utils/HshMap/Gmap";
import {FullScreen, ScaleLine} from "ol/control";
import Glayers from "@/utils/HshMap/Glayers";
import Goverlay from "@/utils/HshMap/Goverlay";
import Ginteraction from "@/utils/HshMap/Ginteraction";
import Gstyle from "@/utils/HshMap/Gstyle";
import PublicInterface from "@/utils/Common/PublicInterface";

@connect(({ birdsProject }) => ({ birdsProject }))
class BirdsProject extends React.Component {


  constructor(props) {
    super(props);

    this.state = {
      birdsUrl: null,
      tableId: null,
      description: null,
      iconLoading: false,
      isopen: false,
      time: null,
      birdType: null,
      birdSeason: null,
      mapLayer: null,
      birdsInfo: {},
      width: 1366,
      height: 768,
      tableColsList: {}
    }
    this.selectOverlay = null;
    this.featureSelected = null;
    this.gmap = new Gmap();
    this.gmap.initMap();
    this.gmap.map.addControl(new FullScreen({tipLabel: '全屏切换'}));

  }

  componentDidMount() {
    this.init();
    this.gmap.map.setTarget('birdsProjectMap');

    // 窗口resize 监听
    this.handleResize();
    window.addEventListener('resize', this.handleResize);

    this.ginteraction = new Ginteraction(this.gmap.map);
    this.ginteraction.on_pointermove(this.select_hover_callback);
  }

  init = () => {
    this.queryServer();
    var self = this;
    var publicInterface = new PublicInterface();
    publicInterface.pubtabcolsList(this.props,{ifanalysis: 1},function (data) {
      self.setState({
        tableColsList: data
      })
    });
    //请求服务
    publicInterface.pubServiceList(this.props,function (data) {
      if (data && data.data.length > 0) {
        data.data.map(ele => {
          let items = null;
          if (ele.childrens) {
            items = ele.childrens.map(ele1 => {
              if (ele1.mapName == '鸟类资源') {
                self.setState({
                  birdsUrl: ele1.netUrl + ele1.url,
                  tableId: ele1.tableId,
                  description: ele1.description
                })
              }
            });
          }
        });
      }
    });
  }
  // ajax请求
  queryServer = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'birdsProject/birdNamesQuery',
      payload: {},
    });
  }

  birdTypeChange = (value) => {
    this.setState({
      birdType: value
    })
  }

  birdSeasonChange = (value) => {
    this.setState({
      birdSeason: value
    })
  }

  // 加载图层
  addMapLayer = (layerType,where,tableId,description) => {
    const { dispatch } = this.props;
    var vector = new Glayers().addVectorLayer('birdsProject/arcgisFeatureServerQuery',dispatch,where,layerType,4326,description);
    vector.set('id', tableId);
    this.gmap.map.addLayer(vector);
    this.setState({
      mapLayer: vector,
    })
  };

  //查询
  enterIconLoading = () => {
    const {birdType,time,birdSeason,mapLayer,birdsInfo,tableId,birdsUrl,description} = this.state;
    var where = ' status_cd=1 ';
    if(birdType) {
      where = " bird_type='" + birdsInfo[birdType] + "' ";
      var year = new Date(time).getFullYear();
      if(year!=1970) {
        switch (birdSeason) {
          case '1':
            where += " and created_dt >= date '" + year + "-1-1' and created_dt < date '" + year + "-4-1'";
            break;
          case '4':
            where += " and created_dt >= date '" + year + "-4-1' and created_dt < date '" + year + "-7-1'";
            break;
          case '7':
            where += " and created_dt >= date '" + year + "-7-1' and created_dt < date '" + year + "-10-1'";
            break;
          case '10':
            where += " and created_dt >= date '" + year + "-10-1' and created_dt < date '" + (Number(year) + 1) + "-1-1'";
            break;
          default:
            where += " and created_dt >= date '" + year + "-1-1' and created_dt < date '" + (Number(year) + 1) + "-1-1'";
            break;
        }
      }
    }
    this.gmap.map.removeLayer(mapLayer);
    this.setState({
      mapLayer: null
    })
    this.addMapLayer(birdsUrl,where,tableId,description);
  };

  //取消Loading
  handleCancel = () => {
    this.setState({
      iconLoading: false,
    });
  };
  // 取父div的height
  handleResize = () => {
    const self = this;
    const divWidth = document.body.clientWidth;
    const divHeight = document.body.clientHeight;
    self.setState({ width: divWidth, height: divHeight - 66 });
    setTimeout(function () {
      self.gmap.map.updateSize();
    }, 100);
  };
  //hover要素
  select_hover_callback = (e) => {
    if (e.dragging) {
      return;
    }
    var self = this;
    var pupupProperties ={};
    self.clearStyle();
    self.gmap.map.forEachFeatureAtPixel(e.pixel, function (f, layer) {
      self.clearStyle();
      self.featureSelected = f;
      f.setStyle(Gstyle.pointermove_style);
      let coodinate = e.coordinate;
      let properties = f.getProperties();
      if(layer!=null && layer.values_.id!=null) {
        if(self.state.tableColsList[layer.values_.id]!=null && self.state.tableColsList[layer.values_.id].length > 0){
          self.state.tableColsList[layer.values_.id].forEach(item => {
            if(item.columnType == "timestamp"){
              pupupProperties[item.description] = properties[item.columnName] ? new Date(properties[item.columnName]).toLocaleDateString() : '--';
            }else {
              pupupProperties[item.description] = properties[item.columnName] ? properties[item.columnName] : '--';
            }
          });
          var overlay = Goverlay.getOverlay_default('hover', coodinate, 1, pupupProperties);
          self.selectOverlay = overlay;
          self.gmap.map.addOverlay(overlay);
        }
      }
    });

  }

  clearStyle = () => {
    var self = this;
    if (self.selectOverlay){
      self.selectOverlay.setPosition(undefined);
      self.selectOverlay = null;
    }
    if (self.featureSelected){
      self.featureSelected.setStyle(null);
      self.featureSelected = null;
    }
  }


  render() {
    let birdOptions = null;
    const { birdsInfo } = this.state
    birdOptions = this.props.birdsProject.birdNames.map(ele => {
      birdsInfo[ele.code] = ele.name;
      return (<Option value={ele.code}>{ele.name}</Option>)
    });
    const { isopen, time } = this.state
    return (
      <Layout>
        <Sider width={371} style={{ background: 'rgba(255,255,255,0.9)', padding: '0',borderRight:'1px solid #ddd', position: 'absolute',left: 0,zIndex: 999,height: 'calc(100% - 110px)'}}>
          <div style={{ background: '#EBF5EF',height: '40px',lineHeight: '40px',paddingLeft: '20px' }}><span style={{ fontSize: '12px',color:'#40AF59' }}>鸟类分布</span></div>
          <div style={{padding: '10px 20px' }}>
            <Select
              showSearch
              size={'middle'}
              style={{ width: 330}}
              placeholder="请选择鸟类"
              optionFilterProp="children"
              onChange={e => this.birdTypeChange(e)}
              filterOption={(input, option) =>
                option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
              }
            >
              {birdOptions}
            </Select></div>
          <div style={{padding: '10px 20px' }}>
            <DatePicker
              value={time}
              open={isopen}
              style={{ width: 330}}
              size={'middle'}
              mode="year"
              placeholder="请选择年份"
              format="YYYY"
              onOpenChange={(status) => {
                if(status){
                  this.setState({isopen: true})
                } else {
                  this.setState({isopen: false})
                }
              }}
              onPanelChange={(v) => {
                this.setState({
                  time: v,
                  isopen: false
                })
              }}
              onChange={() => {
                this.setState({time: null})
              }}
            />
          </div>
          <div style={{padding: '10px 20px' }}>
            <Select
              style={{ width: 330}}
              size={'middle'}
              defaultValue={'year'}
              optionFilterProp="children"
              onChange={this.birdSeasonChange}
              filterOption={(input, option) =>
                option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
              }
            >
              <Option value="year">全年</Option>
              <Option value="1">春季</Option>
              <Option value="4">夏季</Option>
              <Option value="7">秋季</Option>
              <Option value="10">冬季</Option>
            </Select>
          </div>
          <div style={{padding: '20px 20px 10px 20px' }}>
            <Button type="primary" size={'middle'} block
                    loading={this.state.iconLoading}
                    onClick={this.enterIconLoading}>
              开始查询
            </Button>
          </div>
        </Sider>
        <Layout style={{ padding: '0' }}>
          <Content
            id="mapContainer"
            style={{
              background: '#fff',
              padding: 0,
              margin: 0,
            }}>
           <div id="birdsProjectMap" style={{height: this.state.height}}></div>
          </Content>
        </Layout>
      </Layout>

    );
  }
}

export default BirdsProject;
